import { defineStore } from "pinia";
import { addCart,getCartList,deleteCart } from "@/apis/cart";
import 'element-plus/theme-chalk/el-message.css'
import { ElMessage } from 'element-plus'
const useCartStore = defineStore('CartStore',{
    state:()=>{
        return {
            cartList: []
        }
    },
    actions:{
        //获取购物车列表
        async getCartList() {
            const token = localStorage.getItem('token')
          if(token) {
            let res = await getCartList()

            this.cartList = res.result
          }
        },
        async addCartList(goods) {
            const token = localStorage.getItem('token')
            if(token) {
                const {skuId, count} = goods;
                let res = await addCart({skuId, count})
               
                this.getCartList()
            }else {
                const item = this.cartList.find(item => goods.skuId == item.skuId)
                if(item) {
                    item.count+= goods.count
                }else {
                    this.cartList.push(goods)
                }
    
            }
       
       
        },
        async delCart(item,index) {
            const token = localStorage.getItem('token')
            if(token) {
               const {skuId,id} = item;
               let ids = [id,skuId]
               let res = await deleteCart(ids)
               console.log(res);
              if(res.result) {
                ElMessage.success('删除成功')
                this.getCartList()
              }else {
                ElMessage.error('删除失败')
                return Promise.reject(new Error('删除失败'))
              }
            }
            else {
                   //根据下标删除数据
            this.cartList.splice(index,1)
            }   
                  
          
        },
        changeSelected(isAll) {
            this.cartList.forEach(item=>item.selected = isAll)
        },
        // 判断cartList里selected的值是否为true,如果全部为true,则返回true,有一个不为true,则为false
        isAllSelected() {
            return this.cartList.every(item=>item.selected)
            },
       //清除购物车所有数据
       clearCart() {
        this.cartList = []
       }
    },
    getters:{
        // 全部商品数量
        counts() {
            return this.cartList.reduce((pre,item)=>pre+item.count,0)
        },
        //全部商品总额
        sum() {
            return this.cartList.reduce((pre,item)=>pre+item.count*item.price,0).toFixed(2)
        },
        //已选商品数量
        selectedCounts() {
            let selectedArr = this.cartList.filter(item=>item.selected)
            return selectedArr.reduce((pre,item)=>pre+item.count,0)
        },
        //已选商品的价钱总和
        selectedSum() {
            let selectedArr = this.cartList.filter(item=>item.selected)
            return selectedArr.reduce((pre,item)=>pre+item.price*item.count,0).toFixed(2)
        }
    },
    persist: true,
})

export default useCartStore